package com.example.controller;

import com.example.dto.ProductSearchRequest;
import com.example.model.Product;
import com.example.service.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Optional;

/**
 * 商品控制器
 * 提供商品信息的CRUD操作API
 */
@Slf4j
@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor
public class ProductController {
    
    private final ProductService productService;
    
    /**
     * 创建商品
     */
    @PostMapping
    public ResponseEntity<Product> createProduct(@Valid @RequestBody Product product) {
        log.info("创建商品请求: {}", product.getProductName());
        Product savedProduct = productService.saveProduct(product);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedProduct);
    }
    
    /**
     * 根据ID获取商品信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable String id) {
        log.info("获取商品信息请求: {}", id);
        Optional<Product> product = productService.findById(id);
        return product.map(ResponseEntity::ok)
                     .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 获取所有商品（分页）
     */
    @GetMapping
    public ResponseEntity<Page<Product>> getAllProducts(ProductSearchRequest request) {
        log.info("获取所有商品请求，页码: {}, 大小: {}", request.getPage(), request.getSize());
        Pageable pageable = PageRequest.of(request.getPage(), request.getSize());
        Page<Product> products = productService.findAllProducts(pageable);
        return ResponseEntity.ok(products);
    }
    
    /**
     * 搜索商品（支持多条件）
     */
    @PostMapping("/search")
    public ResponseEntity<?> searchProducts(@RequestBody ProductSearchRequest request) {
        log.info("搜索商品请求: {}", request);
        
        // 根据商品编号查找（精确匹配）
        if (request.getProductCode() != null && !request.getProductCode().isEmpty()) {
            Product product = productService.findByProductCode(request.getProductCode());
            return product != null ? ResponseEntity.ok(product) : ResponseEntity.notFound().build();
        }
        
        // 创建分页对象
        Pageable pageable = PageRequest.of(request.getPage(), request.getSize());
        
        // 根据商品名称查找
        if (request.getProductName() != null && !request.getProductName().isEmpty()) {
            List<Product> products = productService.findByProductName(request.getProductName());
            return ResponseEntity.ok(products);
        }
        
        // 根据价格范围查找
        if (request.getMinPrice() != null && request.getMaxPrice() != null) {
            List<Product> products = productService.findByPriceRange(
                    request.getMinPrice().doubleValue(), 
                    request.getMaxPrice().doubleValue());
            return ResponseEntity.ok(products);
        }
        
        // 根据生产日期范围查找
        if (request.getStartDate() != null && request.getEndDate() != null) {
            List<Product> products = productService.findByProductionDateRange(
                    request.getStartDate(), 
                    request.getEndDate());
            return ResponseEntity.ok(products);
        }
        
        // 根据生产厂家查找
        if (request.getManufacturer() != null && !request.getManufacturer().isEmpty()) {
            List<Product> products = productService.findByManufacturer(request.getManufacturer());
            return ResponseEntity.ok(products);
        }
        
        // 如果没有指定搜索条件，返回分页结果
        return ResponseEntity.ok(productService.findAllProducts(pageable));
    }
    
    /**
     * 更新商品信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(
            @PathVariable String id,
            @Valid @RequestBody Product product) {
        log.info("更新商品信息请求: {}", id);
        product.setId(id);
        Product updatedProduct = productService.updateProduct(product);
        return ResponseEntity.ok(updatedProduct);
    }
    
    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable String id) {
        log.info("删除商品请求: {}", id);
        productService.deleteProduct(id);
        return ResponseEntity.noContent().build();
    }
    
    /**
     * 获取商品总数
     */
    @GetMapping("/count")
    public ResponseEntity<Long> getProductCount() {
        log.info("获取商品总数请求");
        long count = productService.countProducts();
        return ResponseEntity.ok(count);
    }
}